<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>玩家ID匹配调试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .test-section {
            background: rgba(255, 255, 255, 0.1);
            margin: 20px 0;
            padding: 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }

        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background: #45a049;
        }

        .log {
            background: rgba(0, 0, 0, 0.3);
            padding: 10px;
            border-radius: 5px;
            height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }

        .input-group {
            margin: 10px 0;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
        }

        .input-group input {
            width: 100%;
            padding: 8px;
            border: none;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .success {
            color: #4CAF50;
        }

        .error {
            color: #f44336;
        }

        .info {
            color: #2196F3;
        }

        .warning {
            color: #ff9800;
        }

        .debug {
            color: #9c27b0;
        }
    </style>
</head>

<body>
    <h1>🔍 玩家ID匹配调试</h1>

    <div class="test-section">
        <h2>🔧 问题分析</h2>
        <p>从控制台日志可以看到玩家"小狗"已经成功加入房间，但点击准备时显示"找不到当前玩家信息"。</p>
        <p>问题可能在于：</p>
        <ul>
            <li>前端存储的currentPlayerId与后端返回的玩家ID格式不匹配</li>
            <li>玩家列表中的ID字段名不一致（Id vs id）</li>
            <li>localStorage中保存的玩家ID与实际的玩家ID不匹配</li>
        </ul>
    </div>

    <div class="test-section">
        <h2>🔌 连接测试</h2>
        <div class="input-group">
            <label>房间码:</label>
            <input type="text" id="roomCode" value="GAGZJ4" />
        </div>
        <div class="input-group">
            <label>玩家昵称:</label>
            <input type="text" id="playerName" value="小狗" />
        </div>
        <button onclick="testConnection()">连接并加入房间</button>
        <button onclick="debugPlayerInfo()">调试玩家信息</button>
        <button onclick="testReadyFunction()">测试准备功能</button>
    </div>

    <div class="test-section">
        <h2>📊 调试信息</h2>
        <div id="debugInfo"></div>
    </div>

    <div class="test-section">
        <h2>📝 实时日志</h2>
        <div id="log" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <script>
        let connection = null;
        let currentRoomCode = null;
        let currentPlayerName = null;
        let currentPlayerId = null;
        let players = [];

        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const className = type;
            logDiv.innerHTML += `<div class="${className}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        function updateDebugInfo() {
            const debugDiv = document.getElementById('debugInfo');
            debugDiv.innerHTML = `
                <h3>当前状态</h3>
                <p><strong>房间码:</strong> ${currentRoomCode || '未设置'}</p>
                <p><strong>玩家昵称:</strong> ${currentPlayerName || '未设置'}</p>
                <p><strong>当前玩家ID:</strong> ${currentPlayerId || '未设置'}</p>
                <p><strong>连接状态:</strong> ${connection?.state || '未连接'}</p>
                <p><strong>玩家数量:</strong> ${players.length}</p>
                
                <h3>玩家列表</h3>
                <pre>${JSON.stringify(players, null, 2)}</pre>
                
                <h3>localStorage信息</h3>
                <pre>${JSON.stringify({
                globalPlayerName: localStorage.getItem('playerName'),
                roomPlayerInfo: localStorage.getItem(`player_${currentRoomCode}`)
            }, null, 2)}</pre>
            `;
        }

        async function testConnection() {
            try {
                const url = 'http://localhost:5152/gamehub';
                log(`正在连接SignalR: ${url}`, 'info');

                connection = new signalR.HubConnectionBuilder()
                    .withUrl(url)
                    .withAutomaticReconnect()
                    .build();

                // 设置事件处理器
                connection.on('PlayerJoined', (player) => {
                    log(`玩家加入: ${JSON.stringify(player)}`, 'success');
                    updatePlayerList();
                });

                connection.on('PlayerLeft', (playerId) => {
                    log(`玩家离开: ${playerId}`, 'warning');
                    updatePlayerList();
                });

                connection.on('PlayerReady', (playerId, ready) => {
                    log(`玩家准备状态: ${playerId} = ${ready}`, 'info');
                    updatePlayerList();
                });

                connection.on('GameJoined', (game) => {
                    log(`游戏状态更新: ${JSON.stringify(game)}`, 'success');
                    updatePlayerList();
                });

                connection.on('Error', (error) => {
                    log(`错误: ${error}`, 'error');
                });

                await connection.start();
                log('SignalR连接成功', 'success');

                // 加入房间
                currentRoomCode = document.getElementById('roomCode').value;
                currentPlayerName = document.getElementById('playerName').value;

                log(`加入房间: ${currentRoomCode}, 玩家: ${currentPlayerName}`, 'info');
                await connection.invoke('JoinGame', currentRoomCode, currentPlayerName, null);
                log('成功加入房间', 'success');

                updateDebugInfo();
            } catch (error) {
                log(`连接失败: ${error.message}`, 'error');
            }
        }

        async function updatePlayerList() {
            try {
                // 获取房间信息
                const response = await fetch(`http://localhost:5152/api/game/code/${currentRoomCode}`);
                const gameData = await response.json();

                players = gameData.players || gameData.Players || [];
                log(`更新玩家列表: ${JSON.stringify(players)}`, 'debug');

                // 查找当前玩家
                const currentPlayer = players.find(p =>
                    (p.NickName || p.nickName) === currentPlayerName
                );

                if (currentPlayer) {
                    currentPlayerId = currentPlayer.Id || currentPlayer.id;
                    log(`找到当前玩家ID: ${currentPlayerId}`, 'success');
                } else {
                    log(`未找到当前玩家: ${currentPlayerName}`, 'error');
                }

                updateDebugInfo();
            } catch (error) {
                log(`更新玩家列表失败: ${error.message}`, 'error');
            }
        }

        async function debugPlayerInfo() {
            log('=== 开始调试玩家信息 ===', 'debug');

            // 检查localStorage
            const globalPlayerName = localStorage.getItem('playerName');
            const roomPlayerInfo = localStorage.getItem(`player_${currentRoomCode}`);

            log(`全局玩家昵称: ${globalPlayerName}`, 'debug');
            log(`房间玩家信息: ${roomPlayerInfo}`, 'debug');

            // 检查当前玩家ID匹配
            if (currentPlayerId && players.length > 0) {
                log(`当前玩家ID: ${currentPlayerId}`, 'debug');

                // 尝试不同的ID匹配方式
                const matchById = players.find(p => p.Id === currentPlayerId);
                const matchByid = players.find(p => p.id === currentPlayerId);
                const matchByNickName = players.find(p => (p.NickName || p.nickName) === currentPlayerName);

                log(`通过Id匹配: ${matchById ? '成功' : '失败'}`, 'debug');
                log(`通过id匹配: ${matchByid ? '成功' : '失败'}`, 'debug');
                log(`通过昵称匹配: ${matchByNickName ? '成功' : '失败'}`, 'debug');

                if (matchById) {
                    log(`匹配到的玩家: ${JSON.stringify(matchById)}`, 'success');
                } else if (matchByid) {
                    log(`匹配到的玩家: ${JSON.stringify(matchByid)}`, 'success');
                } else if (matchByNickName) {
                    log(`匹配到的玩家: ${JSON.stringify(matchByNickName)}`, 'success');
                } else {
                    log('所有匹配方式都失败了！', 'error');
                }
            }

            log('=== 调试完成 ===', 'debug');
        }

        async function testReadyFunction() {
            if (!connection || !currentRoomCode || !currentPlayerName) {
                log('请先连接并加入房间', 'error');
                return;
            }

            try {
                log('测试准备功能...', 'info');

                // 先调试玩家信息
                await debugPlayerInfo();

                // 尝试设置准备状态
                await connection.invoke('SetReady', currentRoomCode, currentPlayerName, true);
                log('✅ 准备功能测试成功', 'success');
            } catch (error) {
                log(`❌ 准备功能测试失败: ${error.message}`, 'error');
            }
        }

        // 页面加载时初始化
        window.onload = function () {
            log('调试页面已加载', 'info');
            log('请确保后端服务在 http://localhost:5152 运行', 'warning');
        };
    </script>
</body>

</html>